import Express from "express";
import cookieParser from "cookie-parser"; // cookie-parser中间件 读取cookie的
import bodyParser from "body-parser"; // 中间件，文本转json
import logger from "morgan"; // 日志文件
import backRouter from "./routes/backRouter";
import { varifyToken } from "./plugins/jwt";
import { sendAiMessage } from "./plugins/chatAi/chatAi";
var path = require("path");
let app = Express();

app.use(logger("dev"));
// 日志文件
var fs = require("fs");
var accessLogStream = fs.createWriteStream(
  path.join(__dirname, "/log/request.log"),
  { flags: "a", encoding: "utf8" }
);
app.use(logger("combined", { stream: accessLogStream }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(Express.static("public"));
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
//设置中间件，token过期校验
app.use((req, res, next) => {
  //排除login相关的路由和接口
  if (req.url.includes("login")) {
    next();
    return;
  }
  const token = req.headers["authorization"]?.split(" ")[1];
  if (token) {
    const payload = varifyToken(token);
    if (payload) {
      next();
    } else {
      res.status(401).send({ errCode: -1, errInfo: "token过期" });
    }
  } else {
    next();
  }
});

app.post(
  "*",
  bodyParser.urlencoded({ extended: true }),
  function (req, res, next) {
    console.log("收到了请求");
    next();
  }
);
// 测试接口
app.get("/", (req, res) => {

  sendAiMessage('1+1=').then((msgs)=>{
    res.send(msgs);
  })
});
// 后端
app.use("/admin", backRouter);
app.set("port", 3000);
// 错误
app.use(function (err: any, req: any, res: any, next: any) {
  // 只开发环境显示错误
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

// 启动服务器
let server = app.listen(app.get("port"), function () {
  console.log("服务器启动了接口为" + app.get("port"));
});
